/*
 * Channel.cpp
 *
 *  Created on: 30/12/2011
 *      Author: faust
 */

#include "Channel.h"
#include "SampleUtils.h"

Channel::Channel()
{

}

Channel::~Channel()
{
	if (layers != 0) delete[]layers;

}

Channel* Channel::create(JNIEnv* env, jobject channelObject)
{

	Channel* channel = new Channel();

	//LOG("Channel::create - start loading channel");

	jclass jChannelClass = env->GetObjectClass(channelObject);
	jmethodID getLayerCountMethodID = env->GetMethodID(jChannelClass,
													"getLayerCount", "()I");

	if (getLayerCountMethodID == 0)
	{
		LOG("Channel::create - Function getLayerCount not found.");
		return NULL;
	}

	int layerCount = env->CallIntMethod(channelObject, getLayerCountMethodID);
	if (!layerCount)
	{
		LOG("Channel::create - getLayerCount returned zero.");
	}

	channel->layerCount = layerCount;
	channel->layers = new Layer*[layerCount];

	jmethodID getLayerMethodID = env->GetMethodID(jChannelClass,
		"getLayer", "(I)Lcom/Domain/Layer;");

	if (getLayerMethodID == 0)
	{
		LOG("Channel::create - Function getLayer not found.");
		return NULL;
	}

	// Register the Layers
	for (int i = 0; i < layerCount; ++i)
	{

		jobject layerObject = env->CallObjectMethod(channelObject, getLayerMethodID, i);
		if (layerObject == NULL)
		{
			LOG("Channel::create - GetLayer() returned zero pointer");
			return NULL;
		}

		channel->layers[i] = Layer::create(env, layerObject);

	}

	channel->selectedLayer = 0;

	//LOG("Channel::create - channel loaded successfully");
	return channel;
}
